package lc20240607;

import lc20240606.TrieNode;

public class WordDictionary {

    TrieNode root;
    public WordDictionary() {
        root=new TrieNode();
    }
    
    public void addWord(String word) {
        char[] wordArray=word.toCharArray();
        TrieNode cur=root;
        for (int i = 0; i < wordArray.length; i++) {
            if (cur.children.containsKey(wordArray[i])){
                cur=cur.children.get(wordArray[i]);
            }
            else {
                cur.children.put(wordArray[i],new TrieNode());
                cur=cur.children.get(wordArray[i]);
            }
        }
        //设置最后一位为true
        cur.isWord=true;
    }
    
    public boolean search(String word) {

       return searchInNode(root,word,0);
    }
    public boolean searchInNode(TrieNode node,String word,int index){
        if (index==word.length()){
            return node.isWord;
        }
        char currentChar=word.charAt(index);
        if (currentChar=='.'){
            for (TrieNode value : node.children.values()) {
                if (searchInNode(value,word,index+1)){
                    return true;
                }
            }
        }else if (node.children.containsKey(currentChar)){
            return searchInNode(node.children.get(currentChar),word,index+1);
        }
        return false;
    }
}